<template lang="pug">
  div.form-tab-pane.relative(v-show="visible")
    slot
</template>

<script>
import { triggerResize } from '../../utils/dom-utils';
import _ from 'lodash';
export default {
  name: 'FormTabPane',
  props: {
    label: {
      type: String,
      default: null
    },
    name: {
      type: String,
      required: true
    },
    disabled: {
      type: Boolean,
      default() {
        return false;
      }
    },
    errorCount: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      visible: false,
      invalid: this.errorCount || 0,
      formComp: []
    };
  },
  watch: {
    errorCount(nv) {
      this.invalid = nv || 0;
    },
    visible(nv) {
      if (nv) {
        this.$nextTick(triggerResize);
      }
    }
  },
  mounted() {
    this.findFormComp();
    this.listenError();
  },
  methods: {
    listenError() {
      if (this.formComp) {
        const fields = _.flatMap(this.formComp, a => a.fields);
        _.each(fields, formItem => {
          if (formItem._validUnwatch) {
            formItem._validUnwatch();
          }
          formItem._validUnwatch = formItem.$watch('validateState', nv => {
            this.invalid = _.filter(
              fields,
              field => field.validateState === 'error'
            ).length;
          });
        });
      }
    },
    findFormComp(children) {
      const items = children || this.$children;
      _.each(items, item => {
        if (item.$options.name === 'iForm') {
          this.formComp.push(item);
        }
        if (!_.isEmpty(item.$children)) {
          this.findFormComp(item.$children);
        }
      });
    }
  }
};
</script>
